# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: conftest.py
# Time: 10:22


import allure
import pytest
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

from common.data.login_data import data
from common.element.devices import OriginalEquipment
from common.util.api_util import config_data
from common.util.env_util import EnvironmentConfiguration
from common.util.file_util import get_img_error_file_path
from common.util.log_util import GenerateLog
from pages.login.execute import LoginBiz
from pages.transition.execute import TransitionBiz


@pytest.fixture(scope="session")
def log():
    '''生成全局log日志工具'''
    global log
    logg = GenerateLog()
    log = logg.logger()
    # 过滤airtest无用日志，只有错误日志才展示
    logg.file_logger()
    return log


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    '''测试报告失败截图，allure报告与日志中会显示出来'''
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            img_name = get_img_error_file_path()
            img_path = snapshot(filename=img_name)
            with open(img_name, mode="rb") as f:
                file = f.read()
            allure.attach(file, "失败截图", allure.attachment_type.PNG)


@pytest.fixture(scope="session")
def poco(log):
    try:
        log.info("正在启动poco")
        global poco
        poco = AndroidUiautomationPoco(use_airtest_input=True,
                                       screenshot_each_action=False)
        log.info("当前运行设备：{}".format(config_data().get("devices")))
        log.info("当前运行环境是：{}".format(config_data().get("environment")))
        log.info("当前程序版本是：{}".format(config_data().get("version")))
        return poco
    except Exception as e:
        log.error("poco启动失败，失败原因：{}".format(e))
        raise


# @pytest.fixture(scope="session")
# # @pytest.mark.parametrize("describe,username,passwor", data.get(EnvironmentConfiguration().get_environment()))
# def login(log, poco):#, describe, username, password
#     try:
#         log.info("开始执行：{}用例操作".format(""))
#         # TransitionBiz(poco, log).transition()
#         LoginBiz(poco, log).login("18574866512", "abc123")
#     except Exception as e:
#         log.error("{}：登录失败，无法进入后续操作:{}".format("username", e))
#         raise


@pytest.fixture(scope="session")
def interim(poco, log):
    try:
        log.info("检测是否安装APP，如果未安装则开始安装，否则卸载后重新安装APP，安装完成后开始加载过渡页面")
        OriginalEquipment(log).open_the_installation()
        TransitionBiz(poco, log).transition()
    except Exception as e:
        log.error("安装APP失败，错误原因：{}".format(e))
